package com.kld.shop.controller.webController;

import com.kld.cms.api.ISysAdService;
import com.kld.cms.api.ISysArticleService;
import com.kld.common.framework.dto.ResultMsg;
import com.kld.common.framework.global.Global;
import com.kld.common.redis.JedisManager;
import com.kld.common.util.DateUtils;
import com.kld.common.util.PropertiesUtil;
import com.kld.promotion.api.IActLogService;
import com.kld.promotion.api.IActivityService;
import com.kld.shop.controller.base.BaseWebController;
import com.kld.third.api.jingdong.IJdAreaService;
import com.kld.third.dto.jingdong.JDArea;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by luyan on 15/8/10.
 * modify by caoz on 16/3/30.
 * problems
 * 1、checkHasCardList
 * 2、商品类别目录树
 */

@Controller
@RequestMapping({"/", "/index"})
public class IndexWebController extends BaseWebController {

    @Autowired
    private IJdAreaService iJdAreaService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private ISysArticleService sysArticleService;
    @Autowired
    private ISysAdService sysAdService;
    @Autowired
    private IActLogService actLogService;
    @RequestMapping("/test")
    public String test() {
        return "/wxapp/returnorder/returnorder";
    }

    @RequestMapping("/test1")
    public String test1() {
        return "/wxapp/returnorder/returnordero";
    }

    @RequestMapping({"/", "index"})
    public ModelAndView Index() {
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> adMap = new HashMap<String, Object>();
        adMap.put("currtime", DateUtils.formatDate(new Date()));
        adMap.put("adtype", 1);
        Object category = JedisManager.getObject("category");
        if(category == null){
            // TODO: 2016/3/30
//            category = productService.getCategoryTree();
            JedisManager.setObject("category",6000,category);
        }
        Object hotcategory = JedisManager.getObject("hotcategory");
        if(hotcategory == null){
            // TODO: 2016/3/30
//            hotcategory = productService.getHotCategoryListNew(5);
            JedisManager.setObject("hotcategory",6000,hotcategory);
        }
        Object hotproduct = JedisManager.getObject("hotproduct");
        if(hotproduct == null){
            // TODO: 2016/3/30
//            hotproduct = productService.getHotProductListNew(10);
            JedisManager.setObject("hotproduct",-1,hotproduct);
        }
        Object proForVehicle = JedisManager.getObject("proForVehicle");
        if(proForVehicle == null){
            proForVehicle = activityService.getLimitJFActList(4);
            JedisManager.setObject("proForVehicle",-1,proForVehicle);
        }
        Object jifenprize = JedisManager.getObject("jifenprize");
        if(jifenprize == null){
            jifenprize = activityService.getLimitJFActList(4);
            JedisManager.setObject("jifenprize",-1,jifenprize);
        }
        Object article = JedisManager.getObject("article");
        if(article == null){
            article = sysArticleService.getArtWebList(5);
            JedisManager.setObject("article",-1,article);
        }
        Object ad = JedisManager.getObject("ad");
        if(ad == null){
            ad = sysAdService.getAdWebList(adMap);
            JedisManager.setObject("ad",-1,ad);
        }
        map.put("category", category);
        map.put("hotcategory", hotcategory);
        map.put("hotproduct", hotproduct);
        map.put("jifenprize", jifenprize);
        map.put("article", article);
        map.put("ad", ad);
        map.put("indexActPro", activityService.getIndexActProList(10));
        return new ModelAndView("index", map);
    }

    @RequestMapping("loginout")
    public void loginout() throws IOException {
        request.getSession().removeAttribute(Global.FRONT_SESSION_USERNAME);
        request.getSession().removeAttribute(Global.FRONT_SESSION_USERID);
        response.sendRedirect("/");
    }


    /**
     * 获取一级地址
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping("getProvinceList")
    public Object getProvinceList() {
        Object province = JedisManager.getObject(Global.JD_PROVICE);
        if(province == null){
            List<JDArea> JDAreaList = iJdAreaService.getProvinceList();
            if(JDAreaList.size()>0){
                JedisManager.setObject(Global.JD_PROVICE,-1,JDAreaList);
                province = JDAreaList;
            }
        }
        ResultMsg resultMsg = new ResultMsg();
        resultMsg.setData(province);
        return resultMsg;
    }


    /**
     * 获取二级地址
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping("getCityList")
    public ResultMsg getCityList(int pid) {
        Object city = JedisManager.getObject(Global.JD_CITY + String.valueOf(pid));
        if(city == null){
            List<JDArea> JDAreaList = iJdAreaService.getCityList(pid);
            if(JDAreaList.size()>0){
                JedisManager.setObject(Global.JD_CITY + String.valueOf(pid),-1,JDAreaList);
                city = JDAreaList;
            }
        }
        ResultMsg resultMsg = new ResultMsg();
        resultMsg.setData(city);
        return resultMsg;
    }

    /**
     * 获取三级地址
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping("getCountyList")
    public ResultMsg getCountyList(int cid) {
        ResultMsg resultMsg = new ResultMsg();
        try {
            Object county = JedisManager.getObject(Global.JD_COUNTY + String.valueOf(cid));
            if(county == null){
                List<JDArea> JDAreaList = iJdAreaService.getCountyList(cid);
                if(JDAreaList.size()>0){
                    JedisManager.setObject(Global.JD_COUNTY + String.valueOf(cid),-1,JDAreaList);
                    county = JDAreaList;
                }
            }
            resultMsg.setData(county);
            resultMsg.setResult(true);
        }catch (Exception e){
            logger.error("获取CountyList出错"+e.getMessage(),e);
            resultMsg.setMsg("获取CountyList出错");
            resultMsg.setResult(false);
        }
        return resultMsg;
    }

    /**
     * 获取四级地址
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping("getTownList")
    public ResultMsg getTownList(int id) {
        ResultMsg resultMsg = new ResultMsg();
        try {
            Object town = JedisManager.getObject(Global.JD_TOWN + String.valueOf(id));
            if(town == null){
                List<JDArea> JDAreaList = iJdAreaService.getTownList(id);
                if(JDAreaList.size()>0){
                    JedisManager.setObject(Global.JD_TOWN + String.valueOf(id),-1,JDAreaList);
                    town = JDAreaList;
                }
            }
            resultMsg.setData(town);
            resultMsg.setResult(true);
        }catch (Exception e){
            logger.error("获取CountyList出错"+e.getMessage(),e);
            resultMsg.setMsg("获取CountyList出错");
            resultMsg.setResult(false);
        }
        return resultMsg;
    }

    /**
     * 模拟登陆
     * @return
     */
    @RequestMapping("/testlogin")
    public ModelAndView testlogin(){
        String tourl = request.getParameter("tourl");
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("tourl", tourl);
        return new ModelAndView("testlogin",map);
    }


    @RequestMapping("/loginsuccess")
    public ModelAndView loginsuccess(){
        String toUrl = request.getParameter("currurl");
        if(StringUtils.isNotBlank(toUrl)){
            toUrl = URLDecoder.decode(toUrl);
        }else {
            toUrl="/index";
        }
        ResultMsg result= actLogService.insertByRegister(getUserID(), getUserName());
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("currurl",toUrl);
        return new ModelAndView("loginsuccess",map);
    }

    @ResponseBody()
    @RequestMapping(value = "getConfigUrl",method = RequestMethod.GET)
    public Map<String,Object> getConfigUrl(){
        String loginurl = PropertiesUtil.props.getProperty("loginUrl");
        String registurl = PropertiesUtil.props.getProperty("registerUrl");
        String portalurl = PropertiesUtil.props.getProperty("portalUrl");
        Map<String,Object> map = new HashMap<String, Object>();
        if("true".equals(PropertiesUtil.props.getProperty("debugMode"))) {
            loginurl = "/testlogin";
        }
        map.put("loginurl",loginurl);
        map.put("registurl",registurl);
        map.put("portalurl",portalurl);
        return map;
    }

    @ResponseBody()
    @RequestMapping(value = "getServerUrl",method = RequestMethod.GET)
    public Map<String,Object> getServerUrl(String currurl){
        String serverurl = "";
        if("true".equals(PropertiesUtil.props.getProperty("debugMode"))) {
            serverurl = URLEncoder.encode(PropertiesUtil.props.getProperty("successCbUrl")+"?currurl="+URLEncoder.encode(currurl));
        }else {
           serverurl = URLEncoder.encode(PropertiesUtil.props.getProperty("successCbUrl")+"?currurl="+URLEncoder.encode(currurl));
        }
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("serverurl",serverurl);
        return map;
    }


    /**
     * 检查是否存在加油卡
     */
    @ResponseBody()
    @RequestMapping(value = "checkHasCardList")
    public ResultMsg checkHasCardList() {
        // TODO: 2016/3/30 card没有做
        ResultMsg rmsg = new ResultMsg();
        rmsg.setResult(true);
//        CardList cardList = null;
//        try {
//            cardList = GenericHTTPSoapClient.sendCardList(getUserID(), 1);
//        } catch (Exception e) {
//            e.printStackTrace();
//            if ("fasle".equals(PropertiesUtil.props.getProperty("debugMode"))) {
//                rmsg.setResult(false);
//                rmsg.setMsg("积分卡查询列表异常");
//            }
//        }
//        if (cardList.getList() != null && cardList.getList().size() > 0) {
//            rmsg.setResult(true);
//        } else {
//            rmsg.setResult(false);
//            rmsg.setData(PropertiesUtil.props.getProperty("bindCardUrl"));
//            rmsg.setMsg("积分卡不存在，请先绑定油卡");
//        }
        return rmsg;
    }

    @RequestMapping("/video")
    public String index(){
        return "video";
    }

}
